package org.spring.aicloud.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.spring.aicloud.utils.AppVariable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author yexiebao
 * @date 2025/6/5
 */
@RestController
public class KafkaController {
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @KafkaListener(topics = AppVariable.CANAL_TOPIC )
    public void canalListen(String message, Acknowledgment acknowledgment) throws JsonProcessingException {
        System.out.println("接收到消息："+message);
        HashMap<String, Object> canalMap = objectMapper.readValue(message, HashMap.class);
        if(!canalMap.isEmpty() && canalMap.get("database").toString().equals("aicloud") &&
                canalMap.get("table").toString().equals("answer")){
            //更新redis缓存
            ArrayList<LinkedHashMap<String, Object>> data = (ArrayList<LinkedHashMap<String, Object>>) canalMap.get("data");

            for (LinkedHashMap<String, Object> map : data) {
                String cacheKey = AppVariable.getListCacheKey(
                        Long.parseLong(map.get("uid").toString()),
                        Integer.parseInt(map.get("model").toString()),
                        Integer.parseInt(map.get("type").toString())
                );
                System.out.println("kafaka缓存键名"+cacheKey);
                redisTemplate.opsForValue().set(cacheKey,null);
                //打印redis缓存
                System.out.println(redisTemplate.opsForValue().get(cacheKey));
            }
        }
        //手动确认应答
        acknowledgment.acknowledge();
    }
}
